<!DOCTYPE html>
<title>View Document</title>
<meta charset=utf-8>
<meta name=viewport content=width=device-width,initial-scale=1>
<style>
  :root {
    background: whitesmoke;
  }

  body {
    margin: 0;
  }

  img {
    display: block;
    box-shadow: 0 1px 2px silver;
    margin: 3em auto;
    max-width: 100%;
  }

  header {
    position: sticky;
    display: flex;
    flex-direction: row;
    align-items: stretch;
    justify-content: space-between;
    zoom: reset;
    top: 0;
    background: white;
    padding: 0.25em;
    box-shadow: 0 1px 1px silver;
  }
  
  header nav {
    flex-grow: 1;
  }

  header div.download {
    text-align: right;
  }

  header div.download a {
    font-size: smaller;
  }

  header, button {
    font-size: 18pt;
  }
</style>
<header>
  <nav>
    <button id=prev>Prev</button>
    <button id=next>Next</button>
    &nbsp;
    <span id=pagenumber></span>
    <button id=rotate>Rotate</button>
  </nav>
  <div class=download>
    <a id=download-link rel=canonical download href=#download>&#x1f5ce; Download the original</a>
  </div>
</header>
<p>
  <span id=loading>Converting...</span>
  &nbsp;
</p>
<img id=page>
<script>
  const path = location.pathname;
  const imgUrl = i => path.replace(/\.html$/,`-${i.toString().padStart(4,'0')}.jpeg`);
  const documentFileName = path.replace(/\.html$/, '');
  console.log({documentFileName});
  const anchor = document.querySelector('#download-link');
  anchor.setAttribute('href', documentFileName);
  let noCram = false;
  let succeeded = false;
  let failed = false;
  let pageNumber = 0;
  let ang = 0;
  page.onerror = () => {
    setTimeout(checkFirstPage, 1001);
  }
  page.onload = () => {
    succeeded = true;
    loading.innerText = ''; 
    pagenumber.innerText = `Page ${(pageNumber + 1)}`;
    page.onerror = checkFirstPage;
  }
  checkFirstPage();
  prev.onclick = () => {
    const nextUrl = imgUrl(--pageNumber);
    if ( noCram ) clearTimeout(noCram);
    noCram = setTimeout(() => {
      noCram = false;
      page.src = nextUrl;
    }, 300);
  };
  next.onclick = () => {
    const nextUrl = imgUrl(++pageNumber);
    if ( noCram ) clearTimeout(noCram);
    noCram = setTimeout(() => {
      noCram = false;
      page.src = nextUrl;
    }, 300);
  }
  rotate.onclick = () => {
    ang = (ang + 90) % 360;
    page.style.transform = `rotate(${ang}deg)`;
  }

  function checkFirstPage() {
    if ( failed ) {
      loading.innerText = 'No such file';
      return;
    }
    pageNumber = 0;
    page.src = imgUrl(pageNumber);
    loading.innerText = 'Converting...';
  }

  setTimeout(() => {
    if ( ! succeeded ) {
      failed = true;
    }
  }, 1000*60*10);
</script>
